package com.example.showcase.acceptor;

import com.example.showcase.common.AbstractBizHandler;
import com.example.showcase.common.Const;
import com.example.showcase.common.Type;
import com.example.showcase.common.handler.*;
import com.example.showcase.server.ShowcaseServerAioHandler;
import com.example.showcase.server.ShowcaseServerAioListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.tio.server.AioServer;
import org.tio.server.ServerGroupContext;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class TCPAcceptor {

    int serverPort = Const.PORT;

    @Autowired
    LoginReqHandler loginReqHandler;
    @Autowired
    HeartbeatReqHandler heartbeatReqHandler;
    @Autowired
    P2PReqHandler p2PReqHandler;
    @Autowired
    JoinGroupReqHandler joinGroupReqHandler;
    @Autowired
    GroupMsgReqHandler groupMsgReqHandler;

    @Bean
    public ShowcaseServerAioHandler showcaseServerAioHandler() {
        ShowcaseServerAioHandler showcaseServerAioHandler = new ShowcaseServerAioHandler();
        Map<Byte, AbstractBizHandler<?>> handlerMap = new HashMap<>();
        handlerMap.put(Type.LOGIN_REQ, loginReqHandler);
        handlerMap.put(Type.HEART_BEAT_REQ, heartbeatReqHandler);
        handlerMap.put(Type.P2P_REQ, p2PReqHandler);
        handlerMap.put(Type.JOIN_GROUP_REQ, joinGroupReqHandler);
        handlerMap.put(Type.GROUP_MSG_REQ, groupMsgReqHandler);
        showcaseServerAioHandler.setHandlerMap(handlerMap);
        return showcaseServerAioHandler;
    }

    @Bean
    ShowcaseServerAioListener showcaseServerAioListener() {
        return new ShowcaseServerAioListener();
    }

    @Bean
    public ServerGroupContext serverGroupContext() {
        ServerGroupContext serverGroupContext = new ServerGroupContext(showcaseServerAioHandler(), showcaseServerAioListener());
        serverGroupContext.setName("Showcase Server");
        return serverGroupContext;
    }

    @Bean
    public TCPAcceptor start(ServerGroupContext serverGroupContext) throws IOException {
        AioServer aioServer = new AioServer(serverGroupContext);
        aioServer.start(null, serverPort);
        return this;
    }

}
